#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 29 17:05:55 2025

@author: ulyanov
"""
# snake.py


import pygame
import numpy as np
from config import *

class Snake:
    def __init__(self):
        self.reset()
    
    def reset(self):
        """重置蛇的状态，初始长度为3节"""
        # 计算初始位置（确保在屏幕范围内）
        start_x = (SCREEN_WIDTH // 2) - (SCREEN_WIDTH // 2) % GRID_SIZE
        start_y = (SCREEN_HEIGHT // 2) - (SCREEN_HEIGHT // 2) % GRID_SIZE
        
        # 初始长度为3节，水平排列
        self.positions = [
            (start_x, start_y),
            (start_x - GRID_SIZE, start_y),
            (start_x - 2 * GRID_SIZE, start_y)
        ]
        self.direction = (GRID_SIZE, 0)  # 初始方向向右
        self.next_direction = (GRID_SIZE, 0)
    
    def change_direction(self, key):
        """根据按键改变蛇的方向"""
        if key == pygame.K_UP and self.direction != (0, GRID_SIZE):
            self.next_direction = (0, -GRID_SIZE)  # 上
        elif key == pygame.K_DOWN and self.direction != (0, -GRID_SIZE):
            self.next_direction = (0, GRID_SIZE)   # 下
        elif key == pygame.K_LEFT and self.direction != (GRID_SIZE, 0):
            self.next_direction = (-GRID_SIZE, 0)  # 左
        elif key == pygame.K_RIGHT and self.direction != (-GRID_SIZE, 0):
            self.next_direction = (GRID_SIZE, 0)   # 右
    
    def move(self):
        """移动蛇"""
        # 确保有蛇头才能移动
        if not self.positions:
            self.reset()
            return
        
        # 更新方向
        self.direction = self.next_direction
        
        # 计算新头部位置
        head_x, head_y = self.positions[0]
        dx, dy = self.direction
        new_head = (head_x + dx, head_y + dy)
        
        # 将新头部添加到蛇身
        self.positions.insert(0, new_head)
    
    def grow(self):
        """增加蛇的长度（在尾部添加一节）"""
        if not self.positions:  # 安全检查
            return
            
        # 获取尾部位置
        tail = self.positions[-1]
        
        if len(self.positions) == 1:
            # 如果只有头部，根据当前方向反方向添加一节
            dx, dy = self.direction
            new_tail = (tail[0] - dx, tail[1] - dy)
        else:
            # 计算尾部移动方向（倒数第二节到尾部的方向）
            prev_tail = self.positions[-2]
            dx = tail[0] - prev_tail[0]
            dy = tail[1] - prev_tail[1]
            new_tail = (tail[0] + dx, tail[1] + dy)
        
        # 添加新尾部
        self.positions.append(new_tail)
        
        # 调试信息
        if hasattr(self, 'debug') and self.debug:
            print(f"蛇增长: 新尾部位置 {new_tail}, 长度 {len(self.positions)}")
    
    def draw(self, surface):
        """绘制蛇"""
        if not self.positions:
            return
            
        for i, position in enumerate(self.positions):
            color = DARK_GREEN if i == 0 else GREEN
            pygame.draw.rect(surface, color, 
                           (position[0], position[1], 
                            GRID_SIZE, GRID_SIZE))